from json import dumps

import requests
from log import Log
from rtc import RTC_Helper

log = Log(tag='HuaweiApi')


class UUID:
    TEMPLATE = '%s-%s-%s%s-%s%s-%s%s%s'

    def __init__(self, date, prefix='87a64c39'):
        self.__prefix = prefix
        self.__date = date
        self.__uuid = None

    @staticmethod
    def as_hex(num, width=2):
        hex_str = hex(num)
        hex_str = hex_str.lstrip('0x')
        return (('0' * width) + hex_str)[-width:]

    def to_string(self):
        if self.__uuid:
            return self.__uuid
        y = UUID.as_hex(self.__date[0], 4)
        m = UUID.as_hex(self.__date[1])
        d = UUID.as_hex(self.__date[2])
        w = UUID.as_hex(self.__date[3])
        h = UUID.as_hex(self.__date[4])
        minute = UUID.as_hex(self.__date[5])
        s = UUID.as_hex(self.__date[6])
        ms = UUID.as_hex(self.__date[7], 8)
        return UUID.TEMPLATE % (self.__prefix, y, m, d, w, h, minute, s, ms)


API_HTTP_HEADERS = {
    'Content-Type': 'application/json;charset=utf-8'
}


class HuaweiApi:
    def __init__(self, config):
        self.__config = config

    def request_token(self):
        log.info('Start request token!')
        # no token

    def post_test(self):
        data = {
            'B': '123123123',
            'H': 1000,
            'L': 2000,
            'W': 3000
        }
        mac = '123123123'
        self.post_data(data, mac)

    def post_data(self, data, mac):
        time = RTC_Helper.current_time()
        time_str = RTC_Helper.current_time_as_string()
        entity_id = self.__config['entityId']
        params_type = self.__config['paramsType']
        uuid = UUID(date=time).to_string()
        warehouse_id = self.__config['warehouseId']

        body = {
            'entityId': entity_id,
            'params': [
                {
                    'carrierNumber': data.get('B'),
                    'deviceId': mac,
                    'height': str(data.get('H')),
                    'width': str(data.get('W')),
                    'length': str(data.get('L')),
                    'type': params_type,
                    'weight': ''
                }
            ],
            'reqCode': uuid,
            'reqTime': time_str,
            'warehouseId': warehouse_id
        }
        url = self.__config['commitUrl']
        body_str = dumps(body)
        try:
            log.debug('HTTP>>>[%s]' % body_str)
            resp = requests.post(url, data=body_str, headers=API_HTTP_HEADERS)
            log.debug('HTTP:<<<[%s]' % resp.text)
            return resp
        except Exception as e:
            log.warn('Error On Http Request [%s]' % url, e)
            return False

    @staticmethod
    def as_result_string(resp):
        if not resp:
            return False, 'NetErr'
        try:
            res_json = resp.json()
        except Exception as e:
            return False, 'E-%s' % repr(e)
        if 'rsCode' in res_json:
            rs_msg = ''
            rs_code = res_json['rsCode']
            if 'rsMsg' in res_json:
                rs_msg = res_json['rsMsg']
            if len(rs_msg) > 128:
                rs_msg = rs_msg[0:128]
            return False, '%s-%s' % (rs_code, rs_msg)
        if 'resultCode' in res_json:
            result_code = res_json['resultCode']
            result_code = result_code.strip()
            result_msg = ''
            if 'resultMsg' in res_json:
                result_msg = res_json['resultMsg']
            if len(result_msg) > 128:
                result_msg = result_msg[0:128]
            if result_code == '0':
                return True, result_msg
            return False, '%s-%s' % (result_code, result_msg)
        return False, resp.text

